/*
 * @Author: xiaosihan 
 * @Date: 2023-05-30 15:24:40 
 * @Last Modified by: 肖思汗
 * @Last Modified time: 2025-06-28 19:22:39
 */
// @ts-nocheck
import get from "lodash/get";
import { CanvasTexture, RepeatWrapping, Texture } from "./myThree/build/three.module";
import FabricCanvas from "./myFabric/FabricCanvas";
import fontManage from "./myFabric/fontManage";
import Taro from "@tarojs/taro";


const LinearEncoding = 3000;

// 纹理管理器
class TextureManager {
    constructor() {
    }

    //创建画布对象
    creatCanvas() {
        // if (utils.isH5) {
        //     const canvas = new OffscreenCanvas(1024, 1024);
        //     return canvas;
        // } else {
        const canvas = Taro.createOffscreenCanvas({
            type: '2d',
            width: 1024,
            height: 1024
        });
        return canvas;
        // }
    }


    // 画布对象
    canvas = this.creatCanvas();

    fabricCanvas = (() => {
        const fabricCanvas = new FabricCanvas();
        return fabricCanvas;
    })();

    // 画布
    canvasMap = new Map();
    // 画布上下文
    ctxMap = new Map();
    // 纹理
    textureMap = new Map<string, Texture>();

    // 透明画布
    transparentCanvasMap = new Map();
    // 透明画布上下文
    transparentCtx = new Map();
    // 透明的纹理
    transparentTextureMap = new Map();

    // 重置纹理
    async init(design_datas) { // : { [key : string] : Object }
        this.canvasMap.clear();
        this.ctxMap.clear();
        this.transparentCanvasMap.clear();
        this.textureMap.clear();
        this.transparentTextureMap.clear();
        for (let name in design_datas) {

            // 创建透明纹理
            const transparentCanvas = this.creatCanvas();
            // transparentCanvas.name = name;
            this.transparentCanvasMap.set(name, transparentCanvas);

            const transparentCtx = transparentCanvas.getContext("2d");
            this.transparentCtx.set(name, transparentCtx);

            const transparentTexture = new CanvasTexture(transparentCanvas);
            // transparentTexture.encoding = LinearEncoding;
            // transparentTexture.wrapS = RepeatWrapping;
            // transparentTexture.wrapT = RepeatWrapping;
            transparentTexture.name = "透明纹理";
            transparentTexture.flipY = false; //翻转纹理
            this.transparentTextureMap.set(name, transparentTexture);

            //加载fabric 数据并绘制到画布上
            await new Promise<void>(async (resolve, reject) => {
                const objects = get(design_datas, ['name', 'objects']) || [];
                // 加载用到的字体
                await fontManage.loadFont(objects.map(o => o.fontFamily));
                // 初始化各部位的纹理图片
                this.fabricCanvas.init(transparentCanvas);
                await this.fabricCanvas.loadFromJSON({ ...design_datas[name], background: "" });
                // this.fabricCanvas.renderAll();
                transparentTexture.needsUpdate = true;
                resolve();
            });

            // 创建带背景的纹理
            const canvas = this.creatCanvas();
            // canvas.name = name;
            this.canvasMap.set(name, canvas);

            const ctx = canvas.getContext("2d");
            this.ctxMap.set(name, ctx);

            const texture = new CanvasTexture(canvas);

            setTimeout(() => {
                texture.needsUpdate = true;
            }, 5000);

            // texture.encoding = LinearEncoding;
            // texture.wrapS = RepeatWrapping;
            // texture.wrapT = RepeatWrapping;
            texture.name = "带背景的纹理";
            texture.flipY = false; //翻转纹理
            this.textureMap.set(name, texture);

            // 把透明背景的纹理绘制到带背景的纹理上, 并绘制背景颜色
            ctx.save();
            if (design_datas[name].background) {
                ctx.fillStyle = design_datas[name].background
                ctx.globalCompositeOperation = "source-over";
                ctx.fillRect(0, 0, 1024, 1024);
            }
            ctx.drawImage(transparentCanvas, 0, 0, transparentCanvas.width, transparentCanvas.height, 0, 0, 1024, 1024);
            ctx.restore();
        }
    }

    //更新指定部位的纹理
    async updata(name, fabricJson) {

        const transparentCanvas = this.transparentCanvasMap.get(name);
        const transparentTexture = this.transparentTextureMap.get(name);

        const texture = textureManager.getTexture(name);
        const ctx = textureManager.getCtx(name);

        if (transparentCanvas && transparentTexture && ctx && texture) {

            const objects = get(fabricJson, ['name', 'objects']) || [];
            // 加载用到的字体
            await fontManage.loadFont(objects.map(o => o.fontFamily));
            // 透明纹理
            this.fabricCanvas.init(transparentCanvas);
            await this.fabricCanvas.loadFromJSON({ ...fabricJson, background: "" });
            transparentTexture.needsUpdate = true;

            // 把透明背景的纹理绘制到带背景的纹理上, 并绘制背景颜色
            ctx.save();
            if (fabricJson.background) {
                ctx.fillStyle = fabricJson.background
                ctx.globalCompositeOperation = "source-over";
                ctx.fillRect(0, 0, 1024, 1024);
            }
            ctx.drawImage(transparentCanvas, 0, 0, transparentCanvas.width, transparentCanvas.height, 0, 0, 1024, 1024);
            ctx.restore();
            texture.needsUpdate = true;
        }
    }

    // 把图像绘制到canvas上 并更新纹理对象
    dwragToCanvas(name, canvas) {
        // const targetCanvas = this.canvasMap.get(name);
        // if (targetCanvas) {
        // 	const targetCtx = targetCanvas.getContext("2d")!;
        // 	targetCtx.clearRect(0, 0, 1024, 1024);
        // 	targetCtx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, 1024, 1024);
        // }

        // const targetTexture = this.textureMap.get(name);
        // if (targetTexture) {
        // 	targetTexture.needsUpdate = true;
        // }

        // // 绘制
        // const targetTransparentCanvas = this.transparentCanvasMap.get(name);
        // if (targetTransparentCanvas) {
        // 	const targetCtx = targetTransparentCanvas.getContext("2d")!;
        // 	targetCtx.clearRect(0, 0, 1024, 1024);
        // 	targetCtx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, 1024, 1024);
        // }

        // const targetTransparentTexture = this.transparentTextureMap.get(name);
        // if (targetTransparentTexture) {
        // 	targetTransparentTexture.needsUpdate = true;
        // }
    }

    // 获取纹理
    getTexture(name) {
        return this.textureMap.get(name);
    }
    //获取画布上下文
    getCtx(name) {
        return this.ctxMap.get(name);
    }
    //获取canvas
    getCanvas(name) {
        return this.canvasMap.get(name);
    }
    // 获取不带背景色的透明贴图
    getTransparentTexture(name) {
        return this.transparentTextureMap.get(name);
    }
    //获取透明canvas的上下文
    getTransparentCtx(name) {
        return this.transparentCtx.get(name);
    }
    // 获取所有透明canvas
    getTransparentCanvas(name) {
        return this.transparentCanvasMap.get(name);
    }

}

const textureManager = new TextureManager();

export default textureManager;